use crate::proj::APP_CONFIG;
use crate::Astr;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::LazyLock;

pub const E_EDIT_ARC: u16 = 101;
pub const E_ROCKSDB: u16 = 102;
pub const E_ARG_MISS: u16 = 106;
pub const E_ARG_BAD: u16 = 107;
pub const E_NO_PERMISSION_FOR_ACTION: u16 = 108;
pub const E_WRONG_KEY_TYPE: u16 = 109;
pub const E_UNKNOWN_CODE: u16 = 1006;

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum UserLocale {
    UlEn,
    UlCn,
}

pub struct TemplateKey(pub u16);

static I18N: LazyLock<HashMap<UserLocale, HashMap<u16, Astr>>> = LazyLock::new(|| {
    fn fill_map(txt: &str, map: &mut HashMap<u16, Astr>) {
        txt.lines().for_each(|x| {
            if x.starts_with("#") || x.len() < 4 {
                return;
            };
            // tracing::info!("{}", x);
            let parts = x.split(":").collect::<Vec<&str>>();
            // tracing::info!("{:?}", parts);
            map.insert(u16::from_str(parts[0]).unwrap(), parts[1].into());
        });
    }
    let mut r = HashMap::<UserLocale, HashMap<u16, Astr>>::new();
    let mut en_map = HashMap::<u16, Astr>::new();
    let txt = include_str!("en.txt");
    fill_map(txt, &mut en_map);
    r.insert(UserLocale::UlEn, en_map);
    let mut cn_map = HashMap::<u16, Astr>::new();
    let txt = include_str!("cn.txt");
    fill_map(txt, &mut cn_map);
    r.insert(UserLocale::UlCn, cn_map);
    r
});

pub fn get_text(k: &TemplateKey) -> Astr {
    let mut r = I18N.get(&APP_CONFIG.lang);
    if r.is_none() {
        r = I18N.get(&UserLocale::UlEn);
    }
    let r = r.unwrap();
    r.get(&k.0)
        .map(|x| x.clone())
        // .map(|x| Arc::from(format!("{}:{}", k.0, x)))
        .expect(format!("no i18n resource of id : {}", k.0).as_ref())
}

pub fn get_and_format_text(k: &TemplateKey, parts: &[&str]) -> Astr {
    let mut s = get_text(k).to_string();
    let mut idx = 0;
    for part in parts {
        s = s.replace(&format!("{{{idx}}}"), &format!("{}", part));
        idx += 1;
    }
    s.into()
}
